"""
Anthropic Claude工具调用功能实现
支持Anthropic Claude模型的工具调用功能
"""
from typing import Dict, Any, List, Optional, Callable
import json
import logging

from ...capabilities.tool_call import ToolCallCapability

logger = logging.getLogger("llm.anthropic.tool")

class AnthropicToolCall(ToolCallCapability):
	"""Anthropic的工具调用实现"""
	
	def _initialize(self) -> None:
		"""初始化工具列表"""
		super()._initialize()
		logger.debug("初始化Anthropic工具调用功能")
	
	def is_supported(self) -> bool:
		"""
		检查当前配置是否支持工具调用
		
		Returns:
			是否支持工具调用
		"""
		# Claude 3系列支持工具调用
		if "claude-3" in self.provider.model.lower():
			return True
		return False
	
	def format_tools_for_request(self) -> List[Dict[str, Any]]:
		"""
		将注册的工具格式化为Anthropic API请求格式
		
		Returns:
			格式化的工具定义列表
		"""
		formatted_tools = []
		
		for name, tool in self._tools.items():
			formatted_tool = {
				"name": tool["name"],
				"description": tool["description"],
				"input_schema": tool["parameters"]
			}
			formatted_tools.append(formatted_tool)
			
		logger.debug(f"格式化了 {len(formatted_tools)} 个工具定义")
		return formatted_tools
		
	def detect_tool_calls(self, response: Dict[str, Any]) -> List[Dict[str, Any]]:
		"""
		检测响应中是否包含工具调用
		
		Args:
			response: API响应
			
		Returns:
			工具调用列表，如果没有则为空列表
		"""
		tool_calls = []
		
		try:
			# Anthropic的工具调用格式
			if "content" in response:
				for content_item in response["content"]:
					if content_item.get("type") == "tool_use":
						tool_calls.append(content_item)
						logger.debug(f"检测到工具调用: {content_item['name']}")
						
		except Exception as e:
			logger.error(f"检测工具调用时出错: {str(e)}")
			
		return tool_calls
	
	def execute_tool_calls(self, tool_calls: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
		"""
		执行工具调用
		
		Args:
			tool_calls: 工具调用列表
			
		Returns:
			工具执行结果列表
		"""
		results = []
		
		for tool_call in tool_calls:
			tool_name = tool_call.get("name")
			tool_id = tool_call.get("id", "unknown_id")
			
			# 检查工具是否注册
			if not tool_name or tool_name not in self._handlers:
				error_result = self.format_tool_response(
					tool_id, 
					tool_name or "unknown",
					{"error": f"工具 '{tool_name}' 未注册"}
				)
				results.append(error_result)
				logger.warning(f"尝试调用未注册的工具: {tool_name}")
				continue
				
			# 解析参数
			try:
				input_val = tool_call.get("input", {})
				if isinstance(input_val, str):
					arguments = json.loads(input_val)
				else:
					arguments = input_val
					
				# 执行工具
				handler = self._handlers[tool_name]
				result = handler(**arguments)
				
				# 格式化结果
				results.append(self.format_tool_response(
					tool_id, 
					tool_name,
					result
				))
				logger.debug(f"成功执行工具: {tool_name}")
			except Exception as e:
				error_result = self.format_tool_response(
					tool_id,
					tool_name,
					{"error": str(e)}
				)
				results.append(error_result)
				logger.error(f"执行工具 {tool_name} 时出错: {str(e)}")
				
		return results
		
	def format_tool_response(self, tool_call_id: str, tool_name: str, result: Any) -> Dict[str, Any]:
		"""
		格式化工具响应消息
		
		Args:
			tool_call_id: 工具调用ID
			tool_name: 工具名称
			result: 工具执行结果
			
		Returns:
			格式化的工具响应消息
		"""
		# 将结果转为字符串（如果不是）
		if not isinstance(result, str):
			result = json.dumps(result, ensure_ascii=False)
			
		return {
			"role": "tool",
			"tool_call_id": tool_call_id,
			"name": tool_name,
			"content": result
		}
